//
//  VOLSelectionViewController.m
//  Volver
//
//  Created by administrator on 14-9-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLSelectionViewController.h"

#import "common.h"
#import "HTTPDefine.h"
#import "VOLAppDelegate.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MJRefresh.h"

#import "VOLSelectionCell.h"
#import "VOLSelectionCellModel.h"
#import "VOLHouseAllInfoViewController.h"
#import "VOLSearchViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <AddressBook/AddressBook.h>

@interface VOLSelectionViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    //定位器
    CLLocationManager *locationManager;
    
    NSFileManager *manager;
    //cell数据来源数组
    NSMutableArray *selectionHouses;
    //记录下次加载房屋信息的位置
    int startIndex;
    
}

@end

@implementation VOLSelectionViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    switch (self.sourceFrom) {
        case 0:
        {//从菜单栏跳转过来
            //添加标题
            self.title = @"精选";
            
            //添加菜单按钮
            addLeftNavigationBarButton();
            
            //添加搜索按钮
            UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
            [searchButton setBackgroundImage:[UIImage imageNamed:@"search_icon.png"] forState:UIControlStateNormal];
            [searchButton addTarget:self action:@selector(searchHouse:) forControlEvents:UIControlEventTouchUpInside];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];
            
            self.cityName = @"";
        }
            break;
        case 1:
        {//当前位置
            self.title = @"定位中...";
            //获取当前城市名
            [self getCurrentCityName];
            addBackButton();
        }
            break;
        case 2:
        {//历史记录中的某一个，搜索
            self.title = self.cityName;
            addBackButton();
        }
            
        default:
            break;
    }
    /*
     //临时注销按钮
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(userLogout:)];
     */
    //初始化
    selectionHouses = [NSMutableArray array];
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    
    startIndex = 0;
    
    //将noticeLabel隐藏，当需要显示时再显示出来
    self.noticeLabel.hidden = YES;
    
    //给tableView添加手势
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    tapGR.numberOfTapsRequired = 1;
    tapGR.numberOfTouchesRequired = 1;
    [self.tableView addGestureRecognizer:tapGR];
    
    [self setupRefresh];
    //加载数据
    //    [self loadHouseDataWithCity:@"苏州"];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 进入界面判断是否刷新
-(void)viewWillAppear:(BOOL)animated{
    if (del.isRefresh == 0 || self.sourceFrom == 1) {
        return;
    }
    del.isRefresh = 0;
    [self.tableView headerBeginRefreshing];
}

#pragma mark - 其它方法
#pragma mark - 设置上拉、下拉
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(selectionRefreshing)];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(selectionLoadMore)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"拼命加载中...";
    
    self.tableView.footerPullToRefreshText = @"加载更多";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载";
    self.tableView.footerRefreshingText = @"拼命加载中...";
}

#pragma mark 下拉刷新方法
-(void)selectionRefreshing{
    //下拉刷新时，要将startIndex置为0
    startIndex = 0;
    
    //先获取当前时间，再根据当前时间加载房屋信息
    
    [self loadHouseDataWithCity:self.cityName];
}

#pragma mark 上拉加载方法
-(void)selectionLoadMore{
    //更新startIndex
    startIndex = selectionHouses.count;
    
    [self loadHouseDataWithCity:self.cityName];
}


#pragma mark 获取当前城市名
-(void)getCurrentCityName{
#pragma mark 定位初始化
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //设置代理
    locationManager.delegate = self;
    
    //开始定位
    [locationManager startUpdatingLocation];
    
}



#pragma mark - 按钮动作
#pragma mark 注销
-(void)userLogout:(id)sender{
    del.isLogin = NO;
    del.currentUser = nil;
    del.currentUser = [[User alloc] init];
    del.isAutologin = 0;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:[NSString stringWithFormat:@"%d",del.isAutologin] forKey:@"isAutoLogin"];
    
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    [del.xmppsteam sendElement:presence];
    
    [del.xmppsteam disconnect];
    [del.rosters removeAllObjects];
}

#pragma mark 菜单按钮的动作
- (void)showMenu:(id)sender {
    kActionOfMenuButton;
}

#pragma mark 返回按钮
-(void)goBack:(id)sender{
    back;
}

#pragma mark 搜索按钮
-(void)searchHouse:(id)sender{
    UINavigationController *navigationController = (UINavigationController *)self.frostedViewController.contentViewController;
    VOLSearchViewController *searchVC = [self.storyboard instantiateViewControllerWithIdentifier:@"searchViewController"];
    navigationController.viewControllers = @[searchVC];
    del.lastIndex = [NSIndexPath indexPathForRow:0 inSection:0];
}


#pragma mark - 手势处理方法
#pragma mark 单击手势动作
-(void)handleTap:(UITapGestureRecognizer *)recognizer{
    NSLog(@"跳转");
    CGPoint point = [recognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
    VOLSelectionCellModel *model = selectionHouses[indexPath.row];
    
    VOLHouseAllInfoViewController *houseAllInfo = [self.storyboard instantiateViewControllerWithIdentifier:@"houseAllInfoController"];
    houseAllInfo.userID = model.houseOwner;
    houseAllInfo.houseID = model.houseID;
    houseAllInfo.sourceFrom = 2;
    [self.navigationController pushViewController:houseAllInfo animated:YES];
}

#pragma mark - 加载方法

#pragma mark 1.网络请求，加载数据
-(void)loadHouseDataWithCity:(NSString *)city{
    
    //将city组装成模糊查询的格式
    NSString *cityStr = [NSString stringWithFormat:@"'%%%@%%'",city];
    
    NSString *urlstr = [NSString stringWithFormat:@"%@house/listDisplay",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //设置请求方式为POST
    [request setRequestMethod:@"POST"];
    //设置代理
    request.delegate = self;
    //设置参数
    [request setPostValue:cityStr forKey:@"houseCity"];
    [request setPostValue:[NSString stringWithFormat:@"%d",startIndex] forKey:@"startIndex"];
    //当前时间
    [request setPostValue:[NSString stringWithFormat:@"%f",kGetCurrentTime] forKey:@"currentTime"];
    [request startAsynchronous];
    
}


#pragma mark 2.1 加载房屋所有图片名字
-(void)getAllHouseImages:(int)houseID array:(NSMutableArray *)imageNameArray{
    NSString *urlstr = [NSString stringWithFormat:@"%@image/searchAllImagesByHouseID?houseID=%d",kHTTPHome,houseID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data) {
        NSDictionary *dic = [jd objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 0) {
            NSLog(@"图片加载失败");
            return;
        }
        
        NSArray *array = [dic objectForKey:@"images"];
        for (NSDictionary *obj in array) {
            [imageNameArray addObject:[obj objectForKey:@"image_name"]];
        }
        
    }else{
        NSLog(@"房屋图片data为空");
        return;
    }
}

#pragma mark - 代理方法

#pragma mark 2.异步请求代理方法
#pragma mark 请求完成的方法：
-(void)requestFinished:(ASIHTTPRequest *)request{
    //先声明一个数组，后面需要时再初始化
    NSMutableArray *newDataArray;
    
    //得到NSData
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"selection----data为空");
        return;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    
    //如果查找失败，提示并返回本方法
    if (!status) {
        NSLog(@"selection-----查找失败");
        //            return;
    }else{
        //查找成功继续解析，取出所查找到的房屋信息
        NSArray *array = [dic objectForKey:@"house"];
        
        //判断是否需要清空数组，当下拉刷新时且数据源数组不为空，清空数组
        if (startIndex == 0 && selectionHouses.count != 0) {
            [selectionHouses removeAllObjects];
        }
        
        //当是上拉时，要初始化这个新数组来接收新来的数据
        if (startIndex != 0) {
            newDataArray = [NSMutableArray array];
        }
        
        
        //遍历数组获取每一个房屋数据，并添加到selectionHouses
        for (NSDictionary *obj in array) {
            VOLSelectionCellModel *model = [[VOLSelectionCellModel alloc] init];
            
            model.houseID = [[obj objectForKey:@"house_id"] intValue];
            model.houseTitle = [obj objectForKey:@"house_title"];
            kGetHouseType(model.houseType, [[obj objectForKey:@"house_type"] intValue]);
            model.houseCity = [NSString stringWithFormat:@"%@%@",[obj objectForKey:@"house_province"],[obj objectForKey:@"house_city"]];
            model.housePrice = [[obj objectForKey:@"house_price"] floatValue];
            model.houseScore = [[obj objectForKey:@"house_score"] floatValue];
            model.houseFacility = [[obj objectForKey:@"house_facility"] intValue];
            model.houseOwner = [[obj objectForKey:@"house_owner"] intValue];
            
            //初始化imageNmaeArray、imageArray
            model.imageNameArray = [NSMutableArray array];
            model.imageArray = [NSMutableArray array];
            
            //调用方法获取房子所有图片名字
            [self getAllHouseImages:model.houseID array:model.imageNameArray];
            
            if (startIndex == 0) {
                //添加model到selectionHouses
                [selectionHouses addObject:model];
            }else{
                //添加model到newDataArray
                [newDataArray addObject:model];
            }
            
            
        }
    }
    if (selectionHouses.count == 0) {
        //显示提示Label
        self.noticeLabel.text = @"这个城市暂时没有房源";
        self.noticeLabel.textColor = kThemeColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.noticeLabel.hidden = NO;
    }else{
        self.noticeLabel.hidden = YES;
    }
    
    if (startIndex == 0) {//下拉刷新
        //刷新tableView
        [self.tableView reloadData];
        //停止刷新
        [self.tableView headerEndRefreshing];
    }else{
        [self.tableView beginUpdates];
        //将新数据插入到tableView中
        [self.tableView insertRowsAtIndexPaths:[self indexPathOfNewlyAddedAssets:newDataArray] withRowAnimation:UITableViewRowAnimationBottom];
        [selectionHouses addObjectsFromArray:newDataArray];
        [self.tableView endUpdates];
        
        [self.tableView footerEndRefreshing];
    }
    
    
    
    
    
}

#pragma mark 转换indexPath方法
- (NSArray *)indexPathOfNewlyAddedAssets:(NSArray *)array
{
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    
    for (NSInteger i = selectionHouses.count; i < selectionHouses.count + array.count ; i++)
        [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    
    return indexPaths;
}

#pragma mark 请求失败的方法：
-(void)requestFailed:(ASIHTTPRequest *)request{
    //停止刷新
    [self.tableView headerEndRefreshing];
    NSLog(@"selection-----请求失败");
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return selectionHouses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"selectionCell";
    VOLSelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    //设置cell的Label上的字体颜色
    cell.housePriceLabel.backgroundColor = kPriceLabelColor;
    cell.housePriceLabel.textColor = [UIColor whiteColor];
    cell.houseTypeLabel.textColor = kPriceLabelColor;
    cell.houseCityLabel.textColor = kPriceLabelColor;
    cell.houseScoreLabel.textColor = kPriceLabelColor;
    
    //给cell上赋值
    VOLSelectionCellModel *cellModel = selectionHouses[indexPath.row];
    cell.housePriceLabel.text = [NSString stringWithFormat:@"￥%.1f",cellModel.housePrice];
    cell.houseTitleLabel.text = cellModel.houseTitle;
    cell.houseTypeLabel.text = cellModel.houseType;
    cell.houseCityLabel.text = cellModel.houseCity;
    cell.houseScoreLabel.text = [NSString stringWithFormat:@"%.1f分",cellModel.houseScore];
    //设置cell上的scrollView的代理
    cell.imagesScrollView.delegate = self;
    
    //如果只有一张图片时，scrollView不滚动
    if (cellModel.imageNameArray.count == 1) {
        cell.imagesScrollView.scrollEnabled = NO;
    }else{
        cell.imagesScrollView.scrollEnabled = YES;
    }
    
    //用cell.tag保存当前行号
    cell.tag = indexPath.row;
    
    //用scrollView的tag来保存当前cell的行号,相当于传递的一个参数
    cell.imagesScrollView.tag = indexPath.row;
    
    //加载scrollView上的图片
    //1.先创建了一个临时数组用来存放下载下来的图片
    [self downloadImages:indexPath cellModel:cellModel];
    
    //2.把这些图片加载到scrollView
    
    
    return cell;
}

#pragma mark cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 270;
}

#pragma mark - 2.2 下载图片
-(void)downloadImages:(NSIndexPath *)indexPath cellModel:(VOLSelectionCellModel *)model{
    
    
    //开启新线程下载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //先从本地查找
        //判断图片文件夹是否存在，若不存在则创建
        NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/houseImages/%d",kGetDocumentsPath,del.currentUser.userID,model.houseID];
        if (![manager fileExistsAtPath:imageDocumentPath]) {
            [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        for (int i = 0; i < model.imageNameArray.count; i++) {
            //得到图片名
            NSString *imageName = model.imageNameArray[i];
            
            //判断图片是否已经保存在本地，如果有则直接加载，如果没有则去下载
            NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,model.houseID,imageName];
            
            //如果本地已存在，直接回到主线程去加载
            if ([manager fileExistsAtPath:imagePath]) {
                UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
                //将图片加入到数组中去
                [model.imageArray addObject:image];
                
                //加载完毕后结束本次循环
                continue;
            }
            
            //如果本地不存在，下载图片
            NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kHouseImageHome,model.houseID,imageName];
            NSURL *url = [NSURL URLWithString:urlstr];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:data];
            if (image != nil) {
                //将图片加入到数组中去
                [model.imageArray addObject:image];
                [data writeToFile:imagePath atomically:YES];
            }
        }
        
        //加载结束后，把图片更新到cell上
        if (model.imageArray.count != 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //获取cell
                VOLSelectionCell *cell = (VOLSelectionCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                [cell setImageScrollVIew:model.imageArray imageIndex:model.imageIndex];
            });
            
        }
    });
    
}

#pragma mark scrollView代理方法

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //如果滑动是由tableView触发的，则不予以理会
    if ([scrollView isKindOfClass:[self.tableView class]]) return;
    
    
    //获取当前cell的行号
    int row = scrollView.tag;
    
    VOLSelectionCell *cell = (VOLSelectionCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    VOLSelectionCellModel *model = selectionHouses[row];
    
    //获取cell上显示图片的index
    int index = model.imageIndex;
    //图片数组count
    int count = model.imageArray.count;
    
    
    
    if (scrollView.contentOffset.x == 640) {
        //        NSLog(@"向左滑--------");
        
        //调用cell的方法，更新scrollView上的图片,1代表向左滑动
        [cell updateImages:model.imageArray index:index direction:1];
        index++;
        
        //最后再将当前的index赋给cell.imageIndex
        model.imageIndex = index % count;
        
    }
    if (scrollView.contentOffset.x == 0) {
        //        NSLog(@"向右滑--------");
        if ((index - 2) < 0) {
            index = index + count;
        }
        [cell updateImages:model.imageArray index:index direction:0];
        index--;
        model.imageIndex = index;
    }
    
    
}

#pragma mark - 定位代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //获取位置的对象
    CLLocation *location = [locations firstObject];
    
    //位置反编码，可以得到当前的位置信息
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark *place in placemarks) {
            
            NSString *city = place.locality;
            
            self.title = city;
            self.cityName = city;
        }
        //        [self.tableView headerBeginRefreshing];
        //定位结束，直接根据城市名查找房源信息
        [self loadHouseDataWithCity:self.cityName];
    }];
    //停止定位
    [locationManager stopUpdatingLocation];
    
}

@end





